package book.security;

import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 用来还原密钥，公钥，私钥
 */
public class KeyFactoryTest {

	public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
		
		KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
		gen.initialize(512);
		KeyPair pair = gen.generateKeyPair();
		byte[] privateKeyBytes = pair.getPrivate().getEncoded();
		byte[] publicKeyBytes = pair.getPublic().getEncoded();
		System.out.println(new BigInteger(privateKeyBytes));
		System.out.println(new BigInteger(publicKeyBytes));
		
		PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyBytes);
		X509EncodedKeySpec spec2 = new X509EncodedKeySpec(publicKeyBytes);
		KeyFactory factory = KeyFactory.getInstance("RSA");
		Key key = factory.generatePrivate(spec);
		Key publicKey = factory.generatePublic(spec2);
		System.out.println(new BigInteger(key.getEncoded()));
		System.out.println(new BigInteger(publicKey.getEncoded()));
	}
}
